package com.nari.ncps.screen.service.impl.al;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlProdoperPrdSit;
import com.nari.ncps.screen.entity.al.AlProdoperPrdSitLd;
import com.nari.ncps.screen.entity.al.AlProdoperPrdSitLy;
import com.nari.ncps.screen.entity.al.AlProdoperPrdSitTsyj;
import com.nari.ncps.screen.mapper.al.AlProdoperPrdSitLdMapper;
import com.nari.ncps.screen.mapper.al.AlProdoperPrdSitLyMapper;
import com.nari.ncps.screen.mapper.al.AlProdoperPrdSitMapper;
import com.nari.ncps.screen.mapper.al.AlProdoperPrdSitTsyjMapper;
import com.nari.ncps.screen.service.al.AlProdoperPrdSitService;
import com.nari.ncps.screen.vo.al.AlProdoperPrdSitVO;
import com.nari.ncps.screen.vo.al.AluminumProductionStatusVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class AlProdoperPrdSitServiceImpl extends ServiceImpl<AlProdoperPrdSitMapper, AlProdoperPrdSit> implements AlProdoperPrdSitService {

    @Autowired
    private AlProdoperPrdSitLyMapper alProdoperPrdSitLyMapper;
    @Autowired
    private AlProdoperPrdSitLdMapper alProdoperPrdSitLdMapper;
    @Autowired
    private AlProdoperPrdSitTsyjMapper alProdoperPrdSitTsyjMapper;


    @Override
    public List<AlProdoperPrdSitVO> getProductionDataByYearAndType(Integer year, Byte productType) {
        // 查询当年数据
        LambdaQueryWrapper<AlProdoperPrdSit> currentYearWrapper = new LambdaQueryWrapper<>();
        currentYearWrapper.eq(AlProdoperPrdSit::getYear, year)
                .eq(AlProdoperPrdSit::getProductType, productType)
                .orderByAsc(AlProdoperPrdSit::getMonth);
        List<AlProdoperPrdSit> currentYearData = this.list(currentYearWrapper);

        // 查询去年同期数据用于计算历史同期生产量
        Integer lastYear = year - 1;
        LambdaQueryWrapper<AlProdoperPrdSit> lastYearWrapper = new LambdaQueryWrapper<>();
        lastYearWrapper.eq(AlProdoperPrdSit::getYear, lastYear)
                .eq(AlProdoperPrdSit::getProductType, productType)
                .orderByAsc(AlProdoperPrdSit::getMonth);
        List<AlProdoperPrdSit> lastYearData = this.list(lastYearWrapper);

        // 将去年数据按月份分组，方便后续查找
        Map<Integer, AlProdoperPrdSit> lastYearDataMap = lastYearData.stream()
                .collect(Collectors.toMap(AlProdoperPrdSit::getMonth, item -> item, (v1, v2) -> v1));

        // 转换为VO
        List<AlProdoperPrdSitVO> voList = new ArrayList<>();
        for (AlProdoperPrdSit entity : currentYearData) {
            AlProdoperPrdSitVO vo = new AlProdoperPrdSitVO();
            BeanUtils.copyProperties(entity, vo);

            // 计算历史同期生产量
            // 如果去年同期有数据，使用去年同期的实际完成量
            AlProdoperPrdSit lastYearSameMonth = lastYearDataMap.get(entity.getMonth());
            if (lastYearSameMonth != null && lastYearSameMonth.getMonthlyActualAmount() != null) {
                vo.setHistoricalProductionAmount(lastYearSameMonth.getMonthlyActualAmount());
            } else {
                // 如果去年没有数据，根据同比率反推：历史同期 = 实际完成量 / (同比率/100)
                if (entity.getMonthlyActualAmount() != null && entity.getYoyRate() != null 
                        && entity.getYoyRate().compareTo(BigDecimal.ZERO) != 0) {
                    BigDecimal historicalAmount = entity.getMonthlyActualAmount()
                            .divide(entity.getYoyRate().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP), 
                                    2, RoundingMode.HALF_UP);
                    vo.setHistoricalProductionAmount(historicalAmount);
                } else {
                    vo.setHistoricalProductionAmount(null);
                }
            }

            voList.add(vo);
        }

        return voList;
    }

    @Override
    public List<AlProdoperPrdSitVO> getRecentSixMonthsData(Integer year, Byte productType) {

        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }
        // 获取当前日期和前6个月的日期
        LocalDate now = LocalDate.now();
        LocalDate sixMonthsAgo = now.minusMonths(5); // 包含当前月，所以减5得到6个月

        // 格式化日期为 statistic_time 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String currentMonth = now.format(formatter);
        String sixMonthsAgoMonth = sixMonthsAgo.format(formatter);
        List<AlProdoperPrdSitVO> resultList = null;
        BigDecimal actualAmountLastYear = new BigDecimal(0);

        if(productType==0){
            resultList = new ArrayList<>();

            LambdaQueryWrapper<AlProdoperPrdSitLy> wrapperMonth = new LambdaQueryWrapper<>();
            wrapperMonth.eq(AlProdoperPrdSitLy::getOrgCode, "100360")
                    .eq(AlProdoperPrdSitLy::getDateType, 1)
                    .eq(AlProdoperPrdSitLy::getYear, year-1)
                    .eq(AlProdoperPrdSitLy::getMonth, LocalDate.now().getMonth());

            List<AlProdoperPrdSitLy> resultMonth = alProdoperPrdSitLyMapper.selectList(wrapperMonth);
            if(resultMonth.size()>0){
                actualAmountLastYear = resultMonth.get(0).getActualAmount();
            }

            LambdaQueryWrapper<AlProdoperPrdSitLy> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AlProdoperPrdSitLy::getOrgCode, "100360")
                    .eq(AlProdoperPrdSitLy::getDateType, 1)
                    .between(AlProdoperPrdSitLy::getStatisticTime, sixMonthsAgoMonth, currentMonth)
                    .orderByAsc(AlProdoperPrdSitLy::getStatisticTime);

            List<AlProdoperPrdSitLy> result = alProdoperPrdSitLyMapper.selectList(wrapper);

//            List<AlProdoperPrdSitVO> resultList = new ArrayList<>();
            for(AlProdoperPrdSitLy item : result) {
                AlProdoperPrdSitVO vo = new AlProdoperPrdSitVO();
                BeanUtils.copyProperties(item, vo);

                vo.setMonthlyPlanAmount(item.getPlanAmount());
                vo.setMonthlyActualAmount(item.getActualAmount());
//                if(item.getCompletionRate()!=null){
                    vo.setMonthlyCompletionRate(item.getCompletionRate());
//                }else{
//                    vo.setMonthlyCompletionRate(item.getActualAmount().divide(item.getPlanAmount(), 4, BigDecimal.ROUND_HALF_UP));
//                }
////                vo.setMonthlyOverShortage(item.getOverShortage());
//                if(item.getOverShortage()!=null){
                    vo.setMonthlyOverShortage(item.getOverShortage());
//                }else{
//                    vo.setMonthlyOverShortage(item.getActualAmount().subtract(item.getPlanAmount()));
//                }

//                vo.setMonthlyCompletionRate(actualAmountLastYear.compareTo(BigDecimal.ZERO)!=0?item.getActualAmount().divide(actualAmountLastYear):BigDecimal.ZERO);

                resultList.add(vo);
            }
        }else if(productType==1){
            resultList = new ArrayList<>();

            LambdaQueryWrapper<AlProdoperPrdSitLd> wrapperMonth = new LambdaQueryWrapper<>();
            wrapperMonth.eq(AlProdoperPrdSitLd::getOrgCode, "100360")
                    .eq(AlProdoperPrdSitLd::getDateType, 1)
                    .eq(AlProdoperPrdSitLd::getYear, year-1)
                    .eq(AlProdoperPrdSitLd::getMonth, LocalDate.now().getMonth());

            List<AlProdoperPrdSitLd> resultMonth = alProdoperPrdSitLdMapper.selectList(wrapperMonth);
            if(resultMonth.size()>0){
                actualAmountLastYear = resultMonth.get(0).getActualAmount();
            }

            LambdaQueryWrapper<AlProdoperPrdSitLd> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AlProdoperPrdSitLd::getOrgCode, "100360")
                    .eq(AlProdoperPrdSitLd::getDateType, 1)
                    .between(AlProdoperPrdSitLd::getStatisticTime, sixMonthsAgoMonth, currentMonth)
                    .orderByAsc(AlProdoperPrdSitLd::getStatisticTime);

            List<AlProdoperPrdSitLd> result = alProdoperPrdSitLdMapper.selectList(wrapper);

//            List<AlProdoperPrdSitVO> resultList = new ArrayList<>();
            for(AlProdoperPrdSitLd item : result) {
                AlProdoperPrdSitVO vo = new AlProdoperPrdSitVO();
                BeanUtils.copyProperties(item, vo);

                vo.setMonthlyPlanAmount(item.getPlanAmount());
                vo.setMonthlyActualAmount(item.getActualAmount());
//                if(item.getCompletionRate()!=null){
                    vo.setMonthlyCompletionRate(item.getCompletionRate());
//                }else{
//                    vo.setMonthlyCompletionRate(item.getActualAmount().divide(item.getPlanAmount(), 4, BigDecimal.ROUND_HALF_UP));
//                }
//                if(item.getOverShortage()!=null){
                    vo.setMonthlyOverShortage(item.getOverShortage());
//                }else{
//                    vo.setMonthlyOverShortage(item.getActualAmount().subtract(item.getPlanAmount()));
//                }
//                vo.setMonthlyOverShortage(item.getOverShortage());
//                vo.setMonthlyCompletionRate(actualAmountLastYear.compareTo(BigDecimal.ZERO)!=0?item.getActualAmount().divide(actualAmountLastYear):BigDecimal.ZERO);

                resultList.add(vo);
            }
        }else if(productType==2){
            resultList = new ArrayList<>();

            LambdaQueryWrapper<AlProdoperPrdSitTsyj> wrapperMonth = new LambdaQueryWrapper<>();
            wrapperMonth.eq(AlProdoperPrdSitTsyj::getOrgCode, "100360")
                    .eq(AlProdoperPrdSitTsyj::getDateType, 1)
                    .eq(AlProdoperPrdSitTsyj::getYear, year-1)
                    .eq(AlProdoperPrdSitTsyj::getMonth, LocalDate.now().getMonth());

            List<AlProdoperPrdSitTsyj> resultMonth = alProdoperPrdSitTsyjMapper.selectList(wrapperMonth);
            if(resultMonth.size()>0){
                actualAmountLastYear = resultMonth.get(0).getActualAmount();
            }

            LambdaQueryWrapper<AlProdoperPrdSitTsyj> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AlProdoperPrdSitTsyj::getOrgCode, "100360")
                    .eq(AlProdoperPrdSitTsyj::getDateType, 1)
                    .between(AlProdoperPrdSitTsyj::getStatisticTime, sixMonthsAgoMonth, currentMonth)
                    .orderByAsc(AlProdoperPrdSitTsyj::getStatisticTime);

            List<AlProdoperPrdSitTsyj> result = alProdoperPrdSitTsyjMapper.selectList(wrapper);

//            List<AlProdoperPrdSitVO> resultList = new ArrayList<>();
            for(AlProdoperPrdSitTsyj item : result) {
                AlProdoperPrdSitVO vo = new AlProdoperPrdSitVO();
                BeanUtils.copyProperties(item, vo);

                vo.setMonthlyPlanAmount(item.getPlanAmount());
                vo.setMonthlyActualAmount(item.getActualAmount());
//                if(item.getCompletionRate()!=null){
                    vo.setMonthlyCompletionRate(item.getCompletionRate());
//                }else{
//                    vo.setMonthlyCompletionRate(item.getActualAmount().divide(item.getPlanAmount(), 4, BigDecimal.ROUND_HALF_UP));
//                }
                vo.setMonthlyOverShortage(item.getOverShortage());
//                if(item.getOverShortage()!=null){
//                    vo.setMonthlyOverShortage(item.getOverShortage());
//                }else{
//                    vo.setMonthlyOverShortage(item.getActualAmount().subtract(item.getPlanAmount()));
//                }
//                vo.setMonthlyCompletionRate(actualAmountLastYear.compareTo(BigDecimal.ZERO)!=0?item.getActualAmount().divide(actualAmountLastYear):BigDecimal.ZERO);

                resultList.add(vo);
            }
//            return resultList;
        }

        return resultList;
    }
    
    @Override
    public AluminumProductionStatusVO getAluminumProductionStatus(String orgCode) {
        AluminumProductionStatusVO vo = new AluminumProductionStatusVO();

        // 查询昨天的数据
        LambdaQueryWrapper<AlProdoperPrdSit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlProdoperPrdSit::getYear, LocalDate.now().getYear())
                .eq(AlProdoperPrdSit::getMonth, LocalDate.now().getMonthValue())
                .eq(AlProdoperPrdSit::getDay, LocalDate.now().minusDays(1).getDayOfMonth())
                .eq(AlProdoperPrdSit::getDateType, 2);//日
        List<AlProdoperPrdSit> allData = this.list(wrapper);

        AluminumProductionStatusVO vo1 = new AluminumProductionStatusVO();
//        vo1.setAluminumLiquidDaily(new BigDecimal(4.57).setScale(2, RoundingMode.HALF_UP));
//        vo1.setAluminumIngotDaily(new BigDecimal(5.61).setScale(2, RoundingMode.HALF_UP));
//        vo1.setCarbonAnodeDaily(new BigDecimal(4.82).setScale(2, RoundingMode.HALF_UP));


//        if (orgCode != null && !orgCode.isEmpty()) {
//            for(AlProdoperPrdSit entity : allData){
//                AluminumProductionStatusVO vo1 = new AluminumProductionStatusVO();
//                vo1.setAluminumIngotDaily(new BigDecimal(4.57));
//                vo1.setAluminumIngotDaily(new BigDecimal(5.61));
//                vo1.setCarbonAnodeDaily(new BigDecimal(4.82));
//
//            }
//        }

//        // 根据orgCode查询铝厂生产情况
//        if (orgCode != null && !orgCode.isEmpty()) {
//            // 获取最近的生产数据
//            int currentYear = LocalDate.now().getYear();
//            List<AlProdoperPrdSitVO> alLiquidData = getRecentSixMonthsData(currentYear, (byte) 0);
//            List<AlProdoperPrdSitVO> alIngotData = getRecentSixMonthsData(currentYear, (byte) 1);
//            List<AlProdoperPrdSitVO> carbonAnodeData = getRecentSixMonthsData(currentYear, (byte) 2);
//
//            if (alLiquidData != null && !alLiquidData.isEmpty()) {
//                AlProdoperPrdSitVO latest = alLiquidData.get(alLiquidData.size() - 1);
//                // 将吨转换为万吨，增加空指针检查
//                if (latest.getMonthlyActualAmount() != null) {
//                    vo.setAluminumLiquidDaily(latest.getMonthlyActualAmount().divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
//                } else {
//                    vo.setAluminumLiquidDaily(BigDecimal.ZERO);
//                }
//            } else {
//                vo.setAluminumLiquidDaily(BigDecimal.ZERO);
//            }
//
//            if (alIngotData != null && !alIngotData.isEmpty()) {
//                AlProdoperPrdSitVO latest = alIngotData.get(alIngotData.size() - 1);
//                if (latest.getMonthlyActualAmount() != null) {
//                    vo.setAluminumIngotDaily(latest.getMonthlyActualAmount().divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
//                } else {
//                    vo.setAluminumIngotDaily(BigDecimal.ZERO);
//                }
//            } else {
//                vo.setAluminumIngotDaily(BigDecimal.ZERO);
//            }
//
//            if (carbonAnodeData != null && !carbonAnodeData.isEmpty()) {
//                AlProdoperPrdSitVO latest = carbonAnodeData.get(carbonAnodeData.size() - 1);
//                if (latest.getMonthlyActualAmount() != null) {
//                    vo.setCarbonAnodeDaily(latest.getMonthlyActualAmount().divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
//                } else {
//                    vo.setCarbonAnodeDaily(BigDecimal.ZERO);
//                }
//            } else {
//                vo.setCarbonAnodeDaily(BigDecimal.ZERO);
//            }
//        }
        
        return vo1;
    }

}
